package com.tanhua.server.service;

import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.model.domain.User;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.server.exception.BusinessException;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {



    @Autowired
    private SmsTemplate smsTemplate;  //发送手机验证码模板

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Autowired
    private RedisTemplate<String ,String> redisTemplate;

    @DubboReference
    private UserApi userApi;


    /**     1.获取手机验证码
     * ***********************************
     *
     *
     */


    /**
     * 获取手机验证码业务层接口
     * @param phone
     * @return
     */
    public String sendMsm(String phone) {

        //1.生成六位数的随机号码
        String randomCode = RandomStringUtils.randomNumeric(6);

//        //2.调用手机验证码模板发送手机验证码
//        smsTemplate.sendSms(phone, randomCode);

        //3.将验证码缓存到Redis中，方便后续比对校验
        redisTemplate.opsForValue().set("CHECK_CODE_"+phone,randomCode, Duration.ofMinutes(5));

        return randomCode;
    }


    /** 2. 手机验证码登录
     * *********************************
     * ************************************
     */


    /**
     * 登录的业务层接口业务逻辑
     * @param phone
     * @param code
     * @return
     */
    public Map loginVerification(String phone, String code) {
        //1.从Redis缓存中获取验证码
        String redisCode = redisTemplate.opsForValue().get("CHECK_CODE_" + phone);
        //2.判断用户输入的验证码与下发的手机验证码是否一致
        //不一致则抛出一个异常
        if(StringUtils.isEmpty(code) || ! redisCode.equals(code)){
            //验证码无效
            throw new BusinessException(ErrorResult.loginError());
        }
        //3.删除Redis中缓存的验证码
        redisTemplate.delete("CHECK_CODE_" + phone);

        //4.dubbo远程调用UserApi,根据手机号码查询用户
        User user = userApi.selectByPhoneNumber(phone);

        boolean isNew =  false;

        //5.如果user为空，证明是新用户，把它存进数据库表
        if(user == null){
            user =new User();
            user.setMobile(phone);
//            user.setCreated(new Date());
//            user.setUpdated(new Date());
            user.setPassword(DigestUtils.md5Hex("123456"));
            Long userId = userApi.addNewUser(user);
            user.setId(userId);
            isNew =true;


            // 用户登录注册成功，信息保存到数据库的同时，还要用户在环信注册账号

            //1.构造环信用户名
            String hx = "hx" +user.getId();
            //2.环信密码
            String passWord = Constants.INIT_PASSWORD;

            //3.注册环信用户
            Boolean result = huanXinTemplate.createUser(hx, passWord);
            //4.注册成功,更新User表
            if(result){
                user.setHxUser(hx);
                user.setHxPassword(passWord);
                userApi.update(user);
            }


        }
        //6.生成token(存入id和手机号码)
        Map userToken = new HashMap();
        userToken.put("id", user.getId());
        userToken.put("phone",phone);

        String token = JwtUtils.getToken(userToken);

        //7.构造返回值
        Map resultMap = new HashMap();

        resultMap.put("token", token);
        resultMap.put("isNew", isNew);

        return resultMap;
    }
}
